package com.yanqu.backendweb.utils;

import com.yanqu.road.utils.TimeHelper;
import org.apache.commons.lang3.StringUtils;
import java.math.BigInteger;


/**
 * @author duli
 * @version 1.0
 * @date 2020/9/23 9:37
 * @Description
 */
public class ReflectionUtil {
    public static Object getValueOf(Class<?> type, String value) {
        if (StringUtils.isEmpty(value)) {
            return defaultValue(type);
        }

        switch (type.getSimpleName()) {
            case "byte":
            case "Byte":
                return Byte.parseByte(value);
            case "short":
            case "Short":
                return Short.parseShort(value);
            case "int":
            case "Integer":
                return Integer.parseInt(value);
            case "BigInteger":
                return BigInteger.valueOf(Long.parseLong(value));
            case "Date":
                return TimeHelper.parseDate(value);
            case "long":
            case "Long":
                return Long.parseLong(value);
            case "float":
            case "Float":
                return Float.parseFloat(value);
            case "double":
            case "Double":
                return Double.parseDouble(value);
            case "boolean":
            case "Boolean":
                return toBoolean(value);
            case "String":
                return value;
            default:
                return null;
        }
    }
    public static Object defaultValue(Class<?> type) {
        switch (type.getSimpleName()) {
            case "String":
                return "";
            case "int":
                return 0;
            case "long":
                return 0L;
            case "double":
                return 0.00D;
            case "boolean":
                return false;
            case "Integer":
            case "Long":
            case "Double":
            case "Boolean":
            default:
                return null;
        }
    }

    public static Boolean toBoolean(String value) {
        if (value == null) {
            throw new IllegalArgumentException();
        }

        switch (value) {
            case "":
            case "null":
            case "NULL":
                return null;
            case "true":
            case "TRUE":
            case "是":
            case "1":
            case "1.0":
                return true;
            case "false":
            case "FALSE":
            case "否":
            case "0":
            case "0.0":
                return false;
            default:
                throw new IllegalArgumentException(value);
        }
    }
}
